package vn.vfriends.vcms.admin.converter;

import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.convert.Converter;
import javax.faces.convert.FacesConverter;
import vn.vfriends.vcms.admin.bean.ItemBean;
import vn.vfriends.vcms.admin.model.Item;

/**
 *
 * @author tuan@vfriends.vn
 */
@FacesConverter(value = "itemConverter")
public class ItemConverter implements Converter {

    @Override
    public Object getAsObject(FacesContext facesContext, UIComponent component, String name) {
        if (name == null || name.length() == 0) {
            return null;
        }
        ItemBean bean = (ItemBean) facesContext.getApplication().getELResolver().getValue(facesContext.getELContext(), null, "itemBean");
        if (bean == null) {
            return null;
        }
        return bean.getItem(name);
    }

    @Override
    public String getAsString(FacesContext facesContext, UIComponent component, Object object) {
        if (object == null || object.equals("")) {
            return null;
        }
        if (object instanceof Item) {
            Item item = (Item) object;
            return item.getName();
        } else {
            throw new IllegalArgumentException("object " + object + " is of type " + object.getClass().getName() + "; expected type: vn.vfriends.vcms.admin.model.Item");
        }
    }
}
